<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/7
 * Time: 9:23
 */

namespace Admin\Frontend\Controllers;

use Helpers\Main;
use Admin\Models\monitor\XhmonitorLicence;
use Helpers\Assets;
use Services\Box;
use Services\Licence;
use Modules\Power;
use Helpers\User;
use Helpers\Template;
class LicenceController extends ControllerBase
{
    private static $iType = [
        0 => '通用',
        9 => '其他',
    ];
    private static $bFree = [
        0 => '收费',
        1 => '免费',
    ];
    private static $iState = [
        0 => '不可用',
        1 => '可用',
    ];

    private static $status = [
        0 => '已绑定',
        1 => '已激活',
        2 => '已过期',
        3 => '已解绑',
    ];


    /**
     * 许可证列表
     *
     *
     * @return string
     *
     * create by zqk 20181127
     */
    public function indexAction()
    {
        if (!Power::exist('LicenceList')) {
            return $this->sendViewError('无许可证管理权限！');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        $this->view->pick('licence/licenceList');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/licence/licenceList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $licenceSearchArr = [];
        $listButtonArr = [];
        $licenceSearchArr[] = ['type' => 'text', 'id' => 'licenceKey', 'label' => ' 许可证Key: '];
        $licenceSearchArr[] = [
            'type' => 'select',
            'label' => ' 是否收费：',
            'id' => 'licenceFree',
            'data' => ['' => '全部'] + self::$bFree,
            'style' => 'margin-left:10px;width:60px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'select',
            'label' => ' 功能分类：',
            'id' => 'licenceType',
            'data' => ['' => '全部'] + self::$iType,
            'style' => 'margin-left:10px;width:80px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'select',
            'label' => ' 状态：',
            'id' => 'licenceState',
            'data' => ['' => '全部'] + self::$iState,
            'style' => 'margin-left:10px;width:80px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'button',
            'id' => 'bt_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        ];
        if (Power::exist('LicenceList_Add')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_add',
                'text' => '新增',
                'icon' => 'fa-plus',
                'style' => 'margin-left:10px'
            ];
        }
        if (Power::exist('LicenceList_Edit')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_edit',
                'text' => '编辑',
                'icon' => 'fa-edit',
                'style' => 'margin-left:10px'
            ];
        }
        $this->view->setVars([
            'licenceList' => Template::createList('licenceList', 'licenceList', [
                'searchToolbar' => Template::createSearchToolBar($licenceSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ]);
    }

    /**
     * 获取许可证列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function getLicenceAction()
    {
        try {
            if (!Power::exist('LicenceList')) {
                return $this->sendErrorResponse(500, '无许可证管理权限');
            }
            $type = $this->request->getPost('iType', 'int'); //根据项目状态太筛选
            $iState = $this->request->getPost('iState', 'int'); //根据项目状态太筛选
            $bFree = $this->request->getPost('bFree', 'int'); //根据项目状态太筛选
            $sKey = $this->request->getPost('sKey', 'string'); //根据项目状态太筛选
            $condition = " bDelete = 0";
            $condition .= in_array($type, self::$iType) ? " AND iType = $type" : '';
            $condition .= in_array($iState, self::$iState) ? " AND iState = $iState" : '';
            $condition .= in_array($bFree, self::$bFree) ? " AND bFree = $bFree" : '';
            $condition .= !empty($sKey) ? " AND sKey LIKE '%$sKey%'" : '';
            $builder = $this->modelsManager->createBuilder()
                ->addFrom('Admin\Models\monitor\XhmonitorLicence')
                ->where($condition)
                ->orderBy("iId desc");
            $data = Main::runBuilderPaginator($builder, true);
            foreach ($data['rows'] as $k => $row) {
                $data['rows'][$k]['iTypeName'] = self::$iType[$row['iType']];
                $data['rows'][$k]['bFreeName'] = self::$bFree[$row['bFree']];
                $data['rows'][$k]['iStateName'] = self::$iState[$row['iState']];
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }


    /**
     * 许可证设备绑定列表
     *
     *
     * @return string
     *
     * create by zqk 20181127
     */
    public function licenceDevAction()
    {
        if (!Power::exist('LicenceDevList')) {
            return $this->sendViewError('无许可证设备绑定列表权限！');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        $this->view->pick('licence/devLicenceList');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/licence/devLicenceList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $licenceSearchArr = [];
        $listButtonArr = [];
        $licenceSearchArr[] = ['type' => 'text', 'id' => 'deviceId', 'label' => ' 设备号: '];
        $licenceSearchArr[] = [
            'type' => 'select',
            'id' => 'licenceType',
            'data' => ['' => '全部'] + self::$iType,
            'style' => 'margin-left:10px;width:80px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'select',
            'id' => 'licenceStatus',
            'data' => ['' => '全部'] + self::$status,
            'style' => 'margin-left:10px;width:80px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'button',
            'id' => 'bt_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        ];
        if (Power::exist('LicenceDevList_Unbind')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_unbind',
                'text' => '解绑',
                'icon' => 'fa-unlink',
                'style' => 'margin-left:10px'
            ];
        }
//        if (Power::exist('LicenceDevList_Active')) {
//            $listButtonArr[] = [
//                'plain' => 'true',
//                'id' => 'bt_list_active',
//                'text' => '激活',
//                'icon' => 'fa-magic',
//                'style' => 'margin-left:10px'
//            ];
//        }
        $this->view->setVars([
            'licenceList' => Template::createList('devLicenceList', 'devLicenceList', [
                'searchToolbar' => Template::createSearchToolBar($licenceSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ]);
    }

    /**
     * 获取设备许可证绑定列表
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by zqk 20181127
     */
    public function getLicenceDevAction()
    {
        if (!Power::exist('LicenceDevList')) {
            return $this->sendErrorResponse(403, '无许可证设备绑定列表权限！');
        }
        $type = $this->request->getPost('type', 'int');
        $status = $this->request->getPost('status', 'int');
        $deviceId = $this->request->getPost('deviceId', 'int');//手动输入
        $page = $this->request->getPost('page', 'int', 1);
        $size = $this->request->getPost('rows', 'int', 50);
        $data = Licence::getLicenceDev($page, $size, $deviceId, $type, $status);
        $datas = [];
        $datas['rows'] = $data['content'];
        $datas['total'] = $data['totalElements'];
        $status = self::$status;
        $type = self::$iType;
        foreach ($datas['rows'] as $k => $v) {
            $datas['rows'][$k]['statusName'] =$status[$v['status']];
            $datas['rows'][$k]['typeName'] =$type[$v['type']];
        };
        return $this->sendJsonResponse($datas);
    }

//    /**
//     * 激活
//     *
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     * @throws \Exception
//     *
//     * create by zqk 20181127
//     */
//    public function activeLicenceDevAction()
//    {
//        if (!Power::exist('LicenceDevList_Active')) {
//            return $this->sendErrorResponse(403, '无许可证设备绑定列表激活权限！');
//        }
//        $id = $this->request->getPost('id');
//        if (empty($id)) {
//            return $this->sendErrorResponse(400, '参数错误！');
//        }
//        try {
//            Licence::activeLicence($id);
//            return $this->sendSuccessResponse('激活成功！');
//        } catch (XhException $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//    }

    /**
     * 解绑
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by zqk 20181127
     */
    public function unbindLicenceDevAction()
    {
        if (!Power::exist('LicenceDevList_Unbind')) {
            return $this->sendErrorResponse(403, '无许可证设备绑定列表激活权限！');
        }
        $id = $this->request->getPost('id', 'int');
        $type = $this->request->getPost('type', 'int');
        $key = $this->request->getPost('key', 'string');
        if (empty($id)) {
            return $this->sendErrorResponse(400, '参数错误！');
        }
        $licenceObj = XhmonitorLicence::findFirst([
            'conditions' => "bDelete = 0 AND iState = 1 AND sKey ='".$key."' AND iType = $type",
        ]);
        if (empty($licenceObj)) {
            return $this->sendErrorResponse(500, '许可证不可用！');
        }
        try {
            Licence::unbindLicence($id);
            $licenceObj->iUseTimes =  $licenceObj->iUseTimes - 1;
            $licenceObj->save();
            return $this->sendSuccessResponse('解绑成功！');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 绑定许可证列表
     *
     *
     * @return string
     *
     * create by zqk 20181127
     */
    public function bindLicenceAction()
    {
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        $this->view->pick('licence/licenceBindList');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/licence/licenceBindList.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $deviceIds = $this->request->get('deviceId');
        if (empty($deviceIds)) {
            return $this->sendViewError('要绑定的设备号为空');
        }
        $licenceSearchArr = [];
        $licenceSearchArr[] = ['type' => 'text', 'id' => 'licenceKey', 'label' => ' 许可证Key: '];
        $licenceSearchArr[] = [
            'type' => 'select',
            'label' => ' 是否收费：',
            'id' => 'licenceFree',
            'data' => ['' => '全部'] + self::$bFree,
            'style' => 'margin-left:10px;width:60px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'select',
            'label' => ' 功能分类：',
            'id' => 'licenceType',
            'data' => ['' => '全部'] + self::$iType,
            'style' => 'margin-left:10px;width:80px;'
        ];
        $licenceSearchArr[] = [
            'type' => 'button',
            'id' => 'bt_search',
            'text' => '查找',
            'icon' => 'fa-search',
            'style' => 'margin-left:10px'
        ];
        $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '提交'];
        $formButtonArr[] = ['id' => 'bt_form_close', 'text' => '取消'];
        $this->view->setVars([
            'FormButton' => Template::createButtonToolBar($formButtonArr),
            'licenceList' => Template::createList('licenceList', 'licenceBindList', [
                'searchToolbar' => Template::createSearchToolBar($licenceSearchArr),
            ]),
            'deviceIds' => $deviceIds,
        ]);
    }

    /**
     * 获取绑定许可证列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     */
    public function getLicenceBindAction()
    {
        try {
            $type = $this->request->getPost('iType', 'int'); //根据项目状态太筛选
            $bFree = $this->request->getPost('bFree', 'int'); //根据项目状态太筛选
            $sKey = $this->request->getPost('sKey', 'string'); //根据项目状态太筛选
            $condition = " bDelete = 0";
            $condition .= " AND iSumTimes - iUseTimes > 0";
            $condition .= in_array($type, self::$iType) ? " AND iType = $type" : '';
            $condition .= " AND iState = 1" ;
            $condition .= in_array($bFree, self::$bFree) ? " AND bFree = $bFree" : '';
            $condition .= !empty($sKey) ? " AND sKey LIKE '%$sKey%'" : '';
            $builder = $this->modelsManager->createBuilder()
                ->addFrom('Admin\Models\monitor\XhmonitorLicence')
                ->where($condition)
                ->orderBy("iId desc");
            $data = Main::runBuilderPaginator($builder, true);
            foreach ($data['rows'] as $k => $row) {
                $data['rows'][$k]['iTypeName'] = self::$iType[$row['iType']];
                $data['rows'][$k]['bFreeName'] = self::$bFree[$row['bFree']];
                $data['rows'][$k]['iStateName'] = self::$iState[$row['iState']];
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 绑定许可证
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Helpers\XhException
     *
     * create by zqk 20181128
     */
    public function bindLicenceDevAction()
    {
        if (!Power::exist('LicenceDevList_Bind')) {
            return $this->sendErrorResponse('500', '无许可证设备绑定权限！');
        }
        $deviceIds = $this->request->getPost('deviceIds');
        if (empty($deviceIds)||!is_array($deviceIds)) {
            return $this->sendErrorResponse(400, '请选择要绑定的设备！');
        }
        $id = $this->request->getPost('id');
        $licenceObj = XhmonitorLicence::findFirst([
            'conditions' => "bDelete = 0 AND iState = 1 AND iSumTimes - iUseTimes > 0 AND iId = $id",
        ]);
        if (empty($licenceObj)) {
            return $this->sendErrorResponse(500, '许可证不可用或不存在！');
        } else {
            $sumtimes = $licenceObj->iSumTimes;
            $usetimes = $licenceObj->iUseTimes;
            $lefttimes = $sumtimes - $usetimes;
            if ($lefttimes < count($deviceIds)) {
                return $this->sendErrorResponse(500, '许可证可用次数只剩'.$lefttimes.'次，请重新选择要绑定的设备！');
            }
        }
        try {
            Licence::bindLicence($deviceIds, $licenceObj->sKey, $licenceObj->iType);
            $licenceObj->iUseTimes =  $licenceObj->iUseTimes + count($deviceIds);
            $licenceObj->save();
            return $this->sendSuccessResponse('绑定成功！');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 新建/编辑 许可证表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181127
     */
    public function licenceFormAction()
    {
        $iId = $this->request->getQuery('iId', 'int');
        $licenceInfo = [];
        if ($iId) {
            if (!Power::exist('LicenceList_Edit')) {
                return $this->sendViewError('无编辑许可证权限');
            }
            $licenceInfo = XhmonitorLicence::findFirst($iId);
            if ($licenceInfo) {
                $licenceInfo = $licenceInfo->toArray();
            }
        } else {
            if (!Power::exist('LicenceList_Add')) {
                return $this->sendViewError('无新增许可证权限');
            }
        }
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::datetimePicker();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/licence/licenceForm.js');
        $this->view->pick('licence/licenceForm');
        $this->view->setVars([
            'iId' => $iId,
            'info' => $licenceInfo,
            'types' => self::$iType,
            'frees' => self::$bFree,
            'states' => self::$iState,
        ]);
    }

    /**
     * 新建/编辑许可证
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180625
     * modify by zqk 20181227
     */
    public function saveLicenceAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        if ($iId) {
            if (!Power::exist('LicenceList_Edit')) {
                return $this->sendErrorResponse(500, '无编辑许可证权限');
            }
        } else {
            if (!Power::exist('LicenceList_Add')) {
                return $this->sendErrorResponse(500, '无新增许可证权限');
            };
        }
        try {
            $this->db->begin();  //开启事务
            if ($iId) {
                $product = XhmonitorLicence::findFirst($iId);
                if (!$product) {
                    return $this->sendErrorResponse(400, '许可证不存在！');
                }
            } else {
                $product = new XhmonitorLicence();
            }
            $product->assign($this->request->getPost());
            $result = $product->save();
            if (!$result) {
                $this->db->rollback();
                return $iId ? $this->sendErrorResponse(500, '编辑许可证失败') : $this->sendErrorResponse(500, '创建许可证失败');
            }
            $this->db->commit();
            return $iId ? $this->sendSuccessResponse('编辑许可证成功') : $this->sendSuccessResponse('创建许可证成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $iId ?
                $this->sendErrorResponse(500, '编辑许可证失败', $exception->getMessage()) :
                $this->sendErrorResponse(500, '创建许可证失败', $exception->getMessage());
        }
    }


}